package com.tyk.bookstore.front.auth.strategy.impl;


import com.tyk.bookstore.front.auth.model.entity.MemberDo;
import com.tyk.bookstore.front.auth.model.query.LoginPwdQuery;
import com.tyk.bookstore.front.auth.repository.MemberAuthRepository;
import com.tyk.bookstore.front.auth.strategy.LoginAction;
import com.tyk.bookstore.front.auth.util.ParamUtil;
import com.tyk.bookstore.front.common.core.model.result.CommonResultEnum;
import com.tyk.bookstore.front.common.core.util.AssertUtil;
import com.tyk.bookstore.front.common.dal.mapper.dto.BinDto;
import com.tyk.bookstore.front.common.other.code.behavior.manager.BehaviorCodeManager;
import com.tyk.bookstore.front.common.other.code.behavior.model.enume.SceneType;
import com.tyk.bookstore.front.common.security.util.PasswordUtil;
import com.tyk.bookstore.front.member.model.result.MemberResultEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.math.BigInteger;

@Component
@RequiredArgsConstructor
public class AccountPwdLoginAction implements LoginAction<LoginPwdQuery> {

    private final MemberAuthRepository memberAuthRepository;
    private final BehaviorCodeManager behaviorCodeManager;

    @Override
    public boolean check(LoginPwdQuery query) {
        return ParamUtil.checkAccount(query.getPrincipal()) && ParamUtil.checkPassword(query.getCertificate());
    }

    @Override
    public Long getMemberId(LoginPwdQuery query) {

        // 校验行为验证码
        boolean check = behaviorCodeManager.check(SceneType.LOGIN, query.getVerifyParam());
        AssertUtil.isTrue(check, CommonResultEnum.CODE_BEHAVIOR_ERROR);

        // 校验账号
        String account = query.getPrincipal();
        BinDto<BigInteger, String> dto = memberAuthRepository
                .selectBin1Eq(
                        MemberDo::getId, MemberDo::getPassword,
                        MemberDo::getAccount, account,
                        MemberDo.class
                );
        boolean f = dto != null && PasswordUtil.checkPassword(query.getCertificate(), dto.getV2());
        AssertUtil.isTrue(f, MemberResultEnum.ACCOUNT_OR_PASSWORD_ERROR);

        // 返回会员ID
        return dto.getV1().longValue();

    }
}
